<template>
  <div class="container mx-auto p-6">
    <!-- 页面标题 -->
    <div class="flex justify-between items-center mb-6">
      <h1 class="text-2xl font-bold text-gray-800">{{ t('新增便携式电池') }}</h1>
      <el-button @click="goBack">
        <i class="el-icon-back mr-1"></i>{{ t('返回列表') }}
      </el-button>
    </div>

    <!-- 表单内容 -->
    <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="180px"
        label-position="left"
        class="bg-white p-6 rounded-lg shadow"
    >
      <template v-for="field in formSections" :key="field.prop">
        <el-form-item
            :label="t(field.label)"
            :prop="field.prop"
            :class="field.spanClass"
        >
          <!-- 输入框 -->
          <el-input
              v-if="field.type === 'input'"
              v-model="formData[field.prop]"
              :placeholder="t(field.placeholder)"
              :clearable="field.clearable"
              :type="field.inputType"
              :rows="field.rows"
          ></el-input>

          <!-- 数字输入框 -->
          <el-input-number
              v-else-if="field.type === 'number'"
              v-model="formData[field.prop]"
              :placeholder="t(field.placeholder)"
              :min="field.min || 0"
              :precision="field.precision || 3"
              :step="field.step || 0.001"
              controls-position="right"
              class="w-full"
          ></el-input-number>

          <!-- 选择器 -->
          <el-select
              v-else-if="field.type === 'select'"
              v-model="formData[field.prop]"
              :placeholder="t(field.placeholder)"
              :clearable="field.clearable"
              class="w-full"
          >
            <el-option
                v-for="option in field.options"
                :key="option.value"
                :label="option.label"
                :value="option.value"
            ></el-option>
          </el-select>

          <!-- 日期选择器 -->
          <el-date-picker
              v-else-if="field.type === 'date'"
              v-model="formData[field.prop]"
              :type="field.dateType"
              :value-format="field.valueFormat"
              :placeholder="t(field.placeholder)"
              class="w-full"
          ></el-date-picker>
        </el-form-item>
      </template>

      <!-- 表单操作按钮 -->
      <div class="flex justify-center gap-4 mt-8 pt-6 border-t">
        <el-button type="primary" @click="handleSubmit" :loading="loading" size="large">
          {{ t('提交') }}
        </el-button>
        <el-button @click="handleReset" :disabled="loading" size="large">
          {{ t('重置') }}
        </el-button>
        <el-button @click="goBack" :disabled="loading" size="large">
          {{ t('取消') }}
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import {reactive, ref} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage, ElMessageBox} from 'element-plus'
import {useI18n} from 'vue-i18n'
import batteryPassportApi from '@/api/portableBatteryApi.js'
import {NCM_ENUM} from "@/api/_const.js"
import {portableBatteryList} from "@/router/index.js";

const { t } = useI18n()
const router = useRouter()
const formRef = ref()
const loading = ref(false)

// 表单数据
const formData = reactive({
  // 基本信息
  batteryPassportId: 'PTL-BXS-202509002' + Math.floor(Math.random() * 1000),
  batteryId: 'LN-X1-C8-BLA' + Math.floor(Math.random() * 1000),
  manufacturerId: 'LNBD-C-B8-2025Q3-00123456',
  batteryCategory: 'lmt',
  manufacturingLocation: '深圳市宝安区石岩街道上屋社区爱群路同富裕工业区4-7#厂房一层-五层',
  manufacturingDate: '2025-09-01 00:00:00',
  batteryMass: 0.5,
  ratedCapacity: 8,

  // 电池材料和组成
  batteryChemistry: 'NCM',
  criticalRawMaterial: '钴、锂、镍、天然石墨',
  hazardousSubstance: '钴',
  substanceImpactDescription: '电解液中的钴属于急性毒性物质',

  // 符号、标签、符合性声明文档
  recyclingSymbolGraphic: 'http://xxx.com',
  cadmiumLeadSymbolGraphic: 'http://xxx.com',
  fireExtinguishingAgent: 'http://xxx.com',
  nonRechargeableGraphic: 'http://xxx.com',
  labelSymbolMeaning: '不可回收标志;不可充电;铅;镉;灭火剂',
  euDeclarationOfConformity: 'http://xxx.com',
  dueDiligenceReport: 'http://xxx.com',

  // 废旧电池预防与管理信息
  wastePreventionInfo: 'http://xxx.com',
  wasteSortingCollectionInfo: 'http://xxx.com',
  batteryEndOfLifeInfo: 'http://xxx.com',
  safetyMeasuresInfo: 'http://xxx.com'
})

const formSections = reactive([

  {prop: 'batteryPassportId',label: '便携式电池护照标识',type: 'input',placeholder: '请输入便携式电池护照标识',clearable: true,required: true},
  {prop: 'batteryId',label: '便携式电池标识',type: 'input',placeholder: '请输入便携式电池标识',clearable: true,required: true},
  {prop: 'manufacturerId',label: '制造商标识符',type: 'input',placeholder: '请输入制造商标识符',clearable: true,required: true},
  {prop: 'manufacturingLocation',label: '制造地点',type: 'input',placeholder: '请输入制造地点',clearable: true,inputType: 'textarea',rows: 2,required: true,spanClass: 'md:col-span-2'},
  {prop: 'manufacturingDate',label: '制造日期',type: 'date',placeholder: '请选择制造日期',dateType: 'month',valueFormat: 'YYYY-MM',required: true},
  {prop: 'batteryMass',label: '便携式电池质量(kg)',type: 'number',placeholder: '请输入电池质量',min: 0,precision: 3,step: 0.001,required: true},
  {prop: 'ratedCapacity',label: '额定容量(Ah)',type: 'number',placeholder: '请输入额定容量',min: 0,precision: 3,step: 0.001,required: true},

  {prop: 'batteryChemistry',label: '电池化学体系',type: 'select',placeholder: '请选择化学体系',clearable: true,required: true,options: NCM_ENUM},
  {prop: 'criticalRawMaterial',label: '关键原材料',type: 'input',placeholder: '请输入关键原材料',clearable: true},
  {prop: 'hazardousSubstance',label: '有害物质',type: 'input',placeholder: '请输入有害物质',clearable: true},
  {prop: 'substanceImpactDescription',label: '物质影响描述',type: 'input',placeholder: '请输入物质对环境、人类健康、安全、人员的影响',clearable: true,inputType: 'textarea',rows: 3,spanClass: 'md:col-span-2'},

  {prop: 'recyclingSymbolGraphic',label: '分类回收符号图形',type: 'input',placeholder: '请输入分类回收符号图形路径',clearable: true},
  {prop: 'cadmiumLeadSymbolGraphic',label: '镉和铅符号图形',type: 'input',placeholder: '请输入镉和铅符号图形路径',clearable: true},
  {prop: 'fireExtinguishingAgent',label: '灭火剂类型',type: 'input',placeholder: '请输入灭火剂类型，如：A，K',clearable: true},
  {prop: 'nonRechargeableGraphic',label: '不可充电符号图形',type: 'input',placeholder: '请输入不可充电符号图形路径',clearable: true},
  {prop: 'labelSymbolMeaning',label: '标签和符号含义',type: 'input',placeholder: '请输入标签和符号的含义，如：铅(Pb)含量超过0.004%',clearable: true,inputType: 'textarea',rows: 2,spanClass: 'md:col-span-2'},
  {prop: 'euDeclarationOfConformity',label: '欧盟符合性声明文档',type: 'input',placeholder: '请输入欧盟符合性声明文档链接',clearable: true},
  {prop: 'dueDiligenceReport',label: '尽职调查报告文档',type: 'input',placeholder: '请输入尽职调查报告文档链接',clearable: true},

  {prop: 'wastePreventionInfo',label: '废物预防信息文档',type: 'input',placeholder: '请输入废物预防信息文档链接',clearable: true},
  {prop: 'wasteSortingCollectionInfo',label: '废物分类收集信息文档',type: 'input',placeholder: '请输入废物分类收集信息文档链接',clearable: true},
  {prop: 'batteryEndOfLifeInfo',label: '电池生命周期信息文档',type: 'input',placeholder: '请输入电池生命周期信息文档链接',clearable: true},
  {prop: 'safetyMeasuresInfo',label: '安全措施信息文档',type: 'input',placeholder: '请输入安全措施信息文档链接',clearable: true},
])

// 动态生成表单验证规则
const formRules = reactive({})


// 提交表单
const handleSubmit = async () => {
  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    loading.value = true

    const res = await batteryPassportApi.createPortableBattery(formData)

    if (res.code === 200) {
      ElMessage.success(t('便携式电池创建成功'))
      await   router.push({name: portableBatteryList})
    } else {
      ElMessage.error(res.message || t('创建失败'))
    }
  } catch (error) {
    console.error('表单提交失败:', error)
  } finally {
    loading.value = false
  }
}

// 重置表单
const handleReset = () => {
  ElMessageBox.confirm(t('确定要重置所有表单数据吗？'), t('提示'), {
    confirmButtonText: t('确定'),
    cancelButtonText: t('取消'),
    type: 'warning'
  }).then(() => {
    formRef.value.resetFields()
    ElMessage.success(t('表单已重置'))
  }).catch(() => {
    // 用户取消操作
  })
}

// 返回列表
const goBack = () => {
  router.push({ name: portableBatteryList })
}

</script>

<style scoped>
:deep(.el-divider__text) {
  background-color: white;
  font-weight: 600;
  color: #409EFF;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style>